const path = require('path');
const fs = require('fs');
const xlsx = require('node-xlsx');
const pako = require('pako');
const formatJson = require('json-beautifully');

let dirPath = path.join(__dirname, "../../excel");
let targetPath = path.join(__dirname, "../../json/configs");

function process() {
    rmDir(targetPath)
    makeDir(targetPath);
    let fileNameArr = readDir(dirPath);
    let filePath = '', sheets = null, sheetsData = null, fileName = '', n = 0;
    for (i = 0; i < fileNameArr.length; i++) {
        if (fileNameArr[i].indexOf('~$') > -1) {
            continue;
        }
        filePath = formatReadPath(dirPath, fileNameArr[i]);
        console.log(filePath, ++n);
        sheets = xlsx.parse(filePath);
        sheetsData = getJsonSaveData(sheets[0].data);
        fileName = fileNameArr[i].split('.')[0];
        writeFile(JSON.stringify(sheetsData, null, '\t'), targetPath + "/" + fileName + ".json", {});
    }
    console.log(' ############### done ###############');
}

function readDir(dirPath) {

    dirPath = absolutePath(dirPath);

    if (!isDir(dirPath)) {
        console.log('utils readDir dir is not exists or isfile dirPath==== ', dirPath);
        return;
    }
    return fs.readdirSync(dirPath);
}

function absolutePath(dirPath) {
    return path.isAbsolute(dirPath) ? dirPath : path.join(__dirname, dirPath);
}

function isDir(dirPath) {
    dirPath = absolutePath(dirPath);
    return fs.existsSync(dirPath) ? fs.statSync(dirPath).isDirectory() : false;
}

function readFile(filePath, asyncFun) {


    if (!fs.existsSync(filePath)) {
        console.log('no file read ====== ', filePath);
        return false;
    }
    if (!asyncFun) {
        try {
            return fs.readFileSync(filePath);
        } catch (e) {
            console.log('readFileSync error === ', e);
        }
    } else {
        fs.readFile(filePath, (err, data) => {
            if (err) return asyncFun(err);
            if (asyncFun) asyncFun(data);
        });
    }
}

function formatReadPath(dirPath, fileName) {
    return path.join(absolutePath(dirPath), fileName ? fileName : '');
}

function getJsonSaveData(excelData, itemSheet) {
    let dataType = excelData[0];
    let title = excelData[1];
    let desc = excelData[2];
    let isClient = excelData[3];
    let ret = null;
    let useFormat1 = false;
    if (useFormat1) {
        let saveData1 = [];// 格式1:对应的为数组
        for (let i = 3; i < excelData.length; i++) {
            let lineData = excelData[i];
            if (lineData.length < title.length) {
                continue;
            } else if (lineData.length > title.length) {
                continue;
            }

            let saveLineData = {};
            for (let j = 0; j < title.length; j++) {
                let key = title[j];
                let value = lineData[j];
                if (value === undefined) {
                    value = "";
                }
                // this._addLog("" + value);
                saveLineData[key] = value;
            }
            saveData1.push(saveLineData);
        }
        ret = saveData1;
    } else {
        // let saveData2 = {};// 格式2:id作为索引
        let saveData2 = [];// 格式2:id作为索引
        for (let i = 4; i < excelData.length; i++) {
            let lineData = excelData[i];
            // if (lineData.length < title.length) {
            //     this._addLog("第" + i+);
            //     continue;
            // } else if (lineData.length > title.length) {
            //     continue;
            // }

            let saveLineData = {};
            for (let j = 0; j < title.length; j++) {
                let key = title[j];
                // key值为下划线_，跳过不读取
                if (key === undefined) {
                    continue;
                }
                let s = key.substr(0, 1);
                if (s == "_") {
                    continue;
                }
                if (!isClient[j]) {
                    continue;
                }
                if (isClient[j].indexOf("c") == -1) {
                    continue;
                }
                let typeD = dataType[j];
                let value = lineData[j];
                if (value === undefined) {
                    value = "";
                }
                // this._addLog("第" + i+ "行，"+"第"+j+"列");
                // this._addLog("title:" + key);
                if (typeD == "table") {
                    if (value) {
                        let parseData = JSON.parse(value);
                        saveLineData[key] = parseData;
                    }

                    // this._addLog("saveLineData[key]："+saveLineData[key]);
                } else {
                    saveLineData[key] = value;
                }
            }
            if (typeof lineData[0] != 'undefined') {
                // saveData2[lineData[0].toString()] = saveLineData;
                saveData2.push(saveLineData);
            }

        }
        ret = saveData2;
    }
    return ret;
}

function writeFile(data, filePath, option, asyncFun) {

    option.flag = option.flag || 'w';
    //同步
    if (!asyncFun) {
        try {
            fs.writeFileSync(filePath, data, option);
            return filePath;
        } catch (e) {
            console.log('writeFileSync ===== ', e);
        }
        //异步
    } else {
        fs.writeFile(filePath, data, option, (err) => {
            if (err) throw err;
            if (asyncFun) {
                let stat = fs.statSync(filePath);
                asyncFun(stat.size);
            }
        });
    }
}

function deleteFile(filePath) {
    if (!fs.existsSync(filePath)) {
        console.log('no file delete ======', filePath);
        return;
    }
    try {
        fs.unlinkSync(filePath);
    } catch (e) {
        console.log('deleteFile ==== ', e);
    }
}

function rmDir(dirName) {
    if (fs.existsSync(dirName)) {
        let fileNameArr = readDir(dirName);
        fileNameArr.forEach(item => {
            let curPath = dirName + "/" + item
            if (isDir(curPath)) {
                rmDir(curPath)
            } else {
                fs.unlinkSync(curPath)
            }
        })
        fs.rmdirSync(dirName)
    }
}

function makeDir(dirPath, option) {
    //需要判断是否是绝对路径(避免不必要的bug)
    dirPath = absolutePath(dirPath);
    //获取相对路径
    dirPath = path.relative(__dirname, dirPath);
    let floders = dirPath.split(path.sep); // path.sep 避免平台差异带来的bug
    let pre = "";
    floders.forEach(floder => {
        try {
            //没有异常，文件已经创建，提示用户改文件已经创建
            let _stat = fs.statSync(path.join(__dirname, pre, floder));
            let hasMkdir = _stat && _stat.isDirectory();
            if (hasMkdir) {
                //console.log(`文件${floder}已经存在，不能重复创建，请重新创建`);
            }
        } catch (error) {
            //抛出异常，文件不存在则创建文件
            try {
                //避免父文件还没有创建的时候先创建子文件所出现的意外bug,这里选择同步创建文件
                fs.mkdirSync(path.join(__dirname, pre, floder), option);
            } catch (e) {
                console.log('makeDir ====  ', e);
            }
        }
        pre = path.join(pre, floder);
    });
    return path.join(__dirname, pre);
}

process();